
/****************************************************************************/
/*Copyright (c) 2011, Florent DEVILLE.                                      */
/*All rights reserved.                                                      */
/*                                                                          */
/*Redistribution and use in source and binary forms, with or without        */
/*modification, are permitted provided that the following conditions        */
/*are met:                                                                  */
/*                                                                          */
/* - Redistributions of source code must retain the above copyright         */
/*notice, this list of conditions and the following disclaimer.             */
/* - Redistributions in binary form must reproduce the above                */
/*copyright notice, this list of conditions and the following               */
/*disclaimer in the documentation and/or other materials provided           */
/*with the distribution.                                                    */
/* - The names of its contributors cannot be used to endorse or promote     */
/*products derived from this software without specific prior written        */
/*permission.                                                               */
/* - The source code cannot be used for commercial purposes without         */ 
/*its contributors' permission.                                             */
/*                                                                          */
/*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       */
/*"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         */
/*LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS         */
/*FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE            */
/*COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,       */
/*INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,      */
/*BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;          */
/*LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER          */
/*CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT        */
/*LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN         */
/*ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           */
/*POSSIBILITY OF SUCH DAMAGE.                                               */
/****************************************************************************/

#include "CSimpleScene.h"
#include "IPrimitive.h"
#include "ILight.h"
#include "IProcTexture.h"
#include "CTexture.h"
#include "CMaterial.h"

#include <limits>
#include <algorithm>

CSimpleScene* CSimpleScene::m_instance = 0;

CSimpleScene::CSimpleScene():m_primitives(), m_lights(), m_materials(), m_textures(), 
	m_globalAmbientLight(0.1f, 0.1f, 0.1f, 1)
{}

CSimpleScene::~CSimpleScene()
{
	for(vector<IPrimitive*>::iterator i = m_primitives.begin(); i != m_primitives.end(); i++)
	{
		delete *i;
	}

	for(vector<ILight*>::iterator i = m_lights.begin(); i != m_lights.end(); i++)
	{
		delete *i;
	}

	for(map<string, CMaterial*>::iterator i = m_materials.begin(); i != m_materials.end(); i++)
	{
		delete (*i).second;
	}

	for(vector<IProcTexture*>::iterator i = m_textures.begin(); i != m_textures.end(); i++)
	{
		delete *i;
	}

	for(vector<CTexture*>::iterator i = m_fileTexture.begin(); i != m_fileTexture.end(); i++)
	{
		delete *i;
	}
}

CSimpleScene& CSimpleScene::getInstance()
{
	if(m_instance == 0)
		m_instance = new CSimpleScene();

	return *m_instance;
}

void CSimpleScene::close()
{
	if(m_instance != 0)
	{
		delete m_instance;
		m_instance = 0;
	}
}

IPrimitive* CSimpleScene::getPrimitive(int index)const
{
	return m_primitives[index];
}

CMaterial* CSimpleScene::getMaterial(const string& materialName)const
{
	map<string, CMaterial*>::const_iterator i = m_materials.find(materialName);
	if(i == m_materials.end())
		return 0;

	return (*i).second;
}

ILight* CSimpleScene::getLight(unsigned int id)const
{
	//check if the index is inside range
	if(id < 0 || id >= m_lights.size())
		return 0;

	//return the light pointer.
	return m_lights[id];
}

IPrimitive* CSimpleScene::removePrimitive(int index)
{
	//get the primitive
	vector<IPrimitive*>::iterator i = m_primitives.begin();
	std::advance(i, index);
	IPrimitive* p = *i;

	//erase it
	m_primitives.erase(i);

	//return the primitive
	return p;
}

int CSimpleScene::getFirstCollision(const CRay& ray, float& dist)
{
	//float min_dist = std::numeric_limits<float>::max(0, 0);
	float min_dist = -1;
	int min_primitive = -1;

	for(vector<IPrimitive*>::iterator i = m_primitives.begin(); i != m_primitives.end(); i++)
	{
		float dist;
		bool test = (*i)->intersect(ray, dist, false);
		if((test && dist < min_dist && dist > 0.01f) ||(test && min_dist == -1 && dist > 0.01f))
		{
			min_primitive = i - m_primitives.begin();
			min_dist = dist;
		}
	}

	if(min_primitive == -1)
		return -1;

	dist = min_dist;
	return min_primitive;
}

bool CSimpleScene::addPrimitive(IPrimitive* primitive)
{
	if(std::find(m_primitives.begin(), m_primitives.end(), primitive) != m_primitives.end())
		return false;

	m_primitives.push_back(primitive);
	return true;
}

bool CSimpleScene::addLight(ILight* light)
{
	if(std::find(m_lights.begin(), m_lights.end(), light) != m_lights.end())
		return false;

	m_lights.push_back(light);
	return true;
}

bool CSimpleScene::addMaterial(CMaterial* material, const string& matName)
{
	if(m_materials.find(matName) != m_materials.end())
		return false;

	m_materials.insert ( pair<string, CMaterial*>(matName, material) );
	return true;
}

bool CSimpleScene::addProcTexture(IProcTexture* texture)
{
	if(std::find(m_textures.begin(), m_textures.end(), texture) != m_textures.end())
		return false;

	m_textures.push_back(texture);
	return true;
}

//store a texture coming from a file
bool CSimpleScene::addFileTexture(CTexture* texture)
{
	if(std::find(m_fileTexture.begin(), m_fileTexture.end(), texture) != m_fileTexture.end())
		return false;

	m_fileTexture.push_back(texture);
	return true;
}
//
//const CColor CSimpleScene::computeLightColor(const CVector3f& view, const CPoint3f& center, const CNormal3f& normal,
//											 const IPrimitive& p)
//{
//	//intersection point in local coordinates
//	CVector3f interLC;
//
//	//get material
//	CMaterial* caracteristics = p.getMaterial();
//	CColor t_color(0, 0, 0);
//
//	//go throught all the lights
//	for(vector<ILight*>::iterator i = m_lights.begin(); i != m_lights.end(); i++)
//	{
//		//compute the shadow ray
//		CRay shadowRay;
//		float lightDistance = -1;
//		(*i)->computeShadowRay(center, shadowRay, &lightDistance);
//		
//		//calculate the intersection point in the local coordinate
//		interLC = center * p.getInverseWorldViewMatrix();
//
//		//check if there is something between the object and the light
//		if(!testCollision(shadowRay, lightDistance)) //no collision
//		{
//			//get the light color and light direction vector
//			CColor lightColor = (*i)->computeColor(shadowRay, lightDistance);
//			CVector3f L = shadowRay.getDirection();
//
//			//LAMBERT
//			float LdotN = L.dot(normal); 
//			if(LdotN > 0.f)
//			{
//				t_color += lightColor * caracteristics->getDiffuse(interLC, p)*LdotN;
//				
//				//PHONG
//				if((*i)->getLightType() == eDirectionalLight)
//					continue;
//				CVector3f lightReflection = L - (normal * 2.0f * LdotN);
//				float dot = view.dot(lightReflection); 
//				if(dot > 0.f)
//					t_color += lightColor * powf(dot, caracteristics->m_shininess)*caracteristics->m_specular;
//
//				//BLINN PHONG
//				/*CVector3f H = L + view;
//				H.normalize();
//				float NdotH = normal.dot(H);
//				if(NdotH > 0.f)
//					t_color += (*i)->getColor()*powf(NdotH, caracteristics.m_shininess)*caracteristics.m_specular;*/
//			}
//		}
//	}
//	
//	//AMBIENT
//	if(caracteristics->useBumpMapping())
//		t_color += normal*caracteristics->getAmbient(interLC)*0.1f;
//	else
//		t_color += caracteristics->getAmbient(interLC)*0.1f;
//
//	//saturate (between 0 and 1)
//	t_color.saturate();
//
//	return t_color;
//}
//
//const CColor CSimpleScene::computeLightColorV2(const CVector3f& view, const CPoint3f& center, const CNormal3f& normal,  
//	const IPrimitive& primitive, const CColor& input)
//{
//	//intersection point in local coordinates
//	CVector3f interLC;
//
//	CColor t_color(0, 0, 0);
//	//get material
//	CMaterial* caracteristics = primitive.getMaterial();
//
//	//go throught all the lights
//	for(vector<ILight*>::iterator i = m_lights.begin(); i != m_lights.end(); i++)
//	{
//		//compute the shadow ray
//		CRay shadowRay;
//		float lightDistance = -1;
//		(*i)->computeShadowRay(center, shadowRay, &lightDistance);
//		
//		//calculate the intersection point in the local coordinate
//		interLC = center * primitive.getInverseWorldViewMatrix();
//
//		//check if there is something between the object and the light
//		if(!testCollision(shadowRay, lightDistance)) //no collision
//		{
//			//get the light color and light direction vector
//			CColor lightColor = (*i)->computeColor(shadowRay, lightDistance);
//			CVector3f L = shadowRay.getDirection();
//
//			//LAMBERT
//			float LdotN = L.dot(normal); 
//			if(LdotN > 0.f)
//			{
//				//t_color += lightColor * caracteristics->getDiffuse(interLC, p)*LdotN;
//				t_color += lightColor * input * LdotN;
//				
//				//PHONG
//				if((*i)->getLightType() == eDirectionalLight)
//					continue;
//				CVector3f lightReflection = L - (normal * 2.0f * LdotN);
//				float dot = view.dot(lightReflection); 
//				if(dot > 0.f)
//					t_color += lightColor * powf(dot, caracteristics->m_shininess)*caracteristics->m_specular;
//
//				//BLINN PHONG
//				/*CVector3f H = L + view;
//				H.normalize();
//				float NdotH = normal.dot(H);
//				if(NdotH > 0.f)
//					t_color += (*i)->getColor()*powf(NdotH, caracteristics.m_shininess)*caracteristics.m_specular;*/
//			}
//		}
//	}
//	
//	//AMBIENT
//	if(caracteristics->useBumpMapping())
//		t_color += normal*caracteristics->getAmbient(interLC)*0.1f;
//	else
//		t_color += caracteristics->getAmbient(interLC)*0.1f;
//
//	//saturate (between 0 and 1)
//	t_color.saturate();
//
//	return t_color;
//}

bool CSimpleScene::testCollision(const CRay& ray, float dist)
{
	for(vector<IPrimitive*>::iterator i = m_primitives.begin(); i != m_primitives.end(); i++)
	{
		float t_dist;
		bool test = (*i)->intersect(ray, t_dist, false);

		if(!test)
			continue;

		if(dist <= 0)
		{
			//if(t_dist>0.1f)//if there is something between 0.01 and infinity
				return true;
		}
		else
		{
			if(t_dist>0.1f && t_dist<dist)//if there is something between 0.01 and dist
				return true;
		}
	}
	return false;
}

void CSimpleScene::applyViewMatrix(const CMatrix& view)
{
	for(vector<IPrimitive*>::iterator i = m_primitives.begin(); i != m_primitives.end(); i++)
		(*i)->applyViewMatrix(view);

	for(vector<ILight*>::iterator i = m_lights.begin(); i != m_lights.end(); i++)
		(*i)->applyViewMatrix(view);
}

//Return the number of source lights in the scene
unsigned int CSimpleScene::getNumberOfLights()const
{
	return m_lights.size();
}

//set the scene global ambient light
void CSimpleScene::setGlobalAmbientLight(const CColor& gal)
{
	m_globalAmbientLight = gal;
}

//get the scene global ambient light
CColor CSimpleScene::getGlobalAmbientLight()const
{
	return m_globalAmbientLight;
}